package com.dashu.school.service;

import com.dashu.base.bean.excel.ExcelStudent;
import com.dashu.base.enums.ReplRyCode;
import com.dashu.base.enums.common.GenderType;
import com.dashu.base.enums.common.PersonalType;
import com.dashu.base.enums.common.Status;
import com.dashu.base.enums.device.Iden;
import com.dashu.base.enums.device.PicType;
import com.dashu.base.utils.CopyUtil;
import com.dashu.base.utils.UIDUtil;
import com.dashu.base.utils.VerificationUtil;
import com.dashu.base.vo.DevicePicAddVO;
import com.dashu.base.vo.DevicePicDelReqVO;
import com.dashu.base.vo.DevicePicUpdReqVO;
import com.dashu.school.dto.company.*;
import com.dashu.school.handler.VerificationException;
import com.dashu.school.model.Company;
import com.dashu.school.model.CompanyPersonal;
import com.dashu.school.model.QCompanyPersonal;
import com.dashu.school.model.Relationship;
import com.dashu.school.result.PageEnty;
import com.dashu.school.vo.UpdateEntityVO;
import com.dashu.school.vo.company.AttendancePersonalListVO;
import com.dashu.school.vo.company.CompanyPersonalListVO;
import com.dashu.school.vo.company.CompanyPersonalVO;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.FlushModeType;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CompanyPersonalService extends DataService {

    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyDepartmentService companyDepartmentService;
    @Autowired
    private CompanyClsService companyClsService;
    @Autowired
    private RelationshipService relationshipService;
    @Autowired
    private DeviceService deviceService;

    @Transactional
    public CompanyPersonalDTO add(CompanyPersonalVO companyPersonalVO, long batchAdd) {
        CompanyPersonal companyPersonal = CopyUtil.copyEnty(companyPersonalVO, CompanyPersonal.class);
        if (isFullStarffed(companyPersonalVO.getClsId()))
            throw new VerificationException(ReplRyCode.CLS_FULL, ReplRyCode.CLS_FULL.getMessage());
        try {
            long userId = Long.parseLong(VerificationUtil.getUserId());
            companyPersonal.setId(UIDUtil.nextId());
            companyPersonal.setCreateUser(userId);
            companyPersonal.setCreateTime(System.currentTimeMillis());
            companyPersonal.setPersonalType(PersonalType.map.get(companyPersonalVO.getPersonalType()));
            companyPersonal.setGender(GenderType.map.get(companyPersonalVO.getGender()));
            if (!StringUtils.isEmpty(companyPersonalVO.getIcon())) {
                companyPersonal.setStatus(Status.INITIALIZATION);
            } else {
                companyPersonal.setStatus(Status.UNINITIALIZED);
            }
            if (batchAdd == 1) {
                CompanyPersonal existPersonal = existPersonal(companyPersonal.getClsId(), companyPersonal.getNum());
                if (existPersonal != null)
                    companyPersonal.setNum(null);
                if (companyPersonalVO.getNum() == null)
                    companyPersonal.setStatus(Status.ERROR);
                if (companyPersonalVO.getPersonalName() == null)
                    companyPersonal.setStatus(Status.ERROR);
                if (companyPersonalVO.getGender() == null)
                    companyPersonal.setStatus(Status.ERROR);
                if (companyPersonalVO.getPersonalType() == null)
                    companyPersonal.setStatus(Status.ERROR);
            }
            entityManager.persist(companyPersonal);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VerificationException(ReplRyCode.DATA_NOT_INVALID, ReplRyCode.DATA_NOT_INVALID.getMessage());
        }
        CompanyPersonalDTO companyPersonalDTO = CopyUtil.copyEnty(companyPersonal, CompanyPersonalDTO.class);
        return companyPersonalDTO;
    }


    @Transactional
    public List<CompanyPersonalDTO> batchAdd(List<ExcelStudent> excelStudents, long companyId, long departmentId, long clsId) {
        CompanyPersonalVO companyPersonalVO = new CompanyPersonalVO();
        companyPersonalVO.setCompanyId(companyId);
        companyPersonalVO.setDepartmentId(departmentId);
        companyPersonalVO.setClsId(clsId);
        List<CompanyPersonalDTO> companyPersonalDTOS = Lists.newArrayList();
        excelStudents.stream().forEach(excelStudent -> {
            String name = excelStudent.getName() == null ? "" : excelStudent.getName();
            companyPersonalVO.setPersonalName(name);
            String num = excelStudent.getNum() == null ? "" : excelStudent.getNum();
            companyPersonalVO.setNum(num);
            String gender = excelStudent.getGender() == null ? "" : excelStudent.getGender().name();
            companyPersonalVO.setGender(gender);
            String personalType = excelStudent.getPersonalType() == null ? "" : excelStudent.getPersonalType().name();
            companyPersonalVO.setPersonalType(personalType);
            companyPersonalDTOS.add(add(companyPersonalVO, 1));


        });
        return companyPersonalDTOS;

    }


    @Transactional
    public boolean isFullStarffed(long clsId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(clsId));
        List<CompanyPersonal> companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetch();
        CompanyClsDTO companyClsDTO = companyClsService.findByCompanyClsId(clsId);
        if (companyPersonals.size() > companyClsDTO.getPeopleNum()) return true;
        return false;

    }

    @Transactional
    public boolean deleteImgPersonal(long companyPersonalId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(companyPersonalId));
        CompanyPersonal companyPersonal =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        DevicePicDelReqVO devicePicDelReqVO = new DevicePicDelReqVO();
        devicePicDelReqVO.setUserId(String.valueOf(companyPersonal.getId()));
        devicePicDelReqVO.setUserName(companyPersonal.getPersonalName());
        devicePicDelReqVO.setIden(Iden.TEACHER);
        devicePicDelReqVO.setResp(companyPersonal.getIcon());
        deviceService.DeldeviceBaseHand(companyPersonal.getCompanyId(), devicePicDelReqVO);

        return true;

    }

    @Transactional
    public boolean updateImgPersonal(long companyPersonalId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(companyPersonalId));
        CompanyPersonal companyPersonal =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        DevicePicUpdReqVO devicePicUpdReqVO = new DevicePicUpdReqVO();
        devicePicUpdReqVO.setUserId(String.valueOf(companyPersonal.getId()));
        devicePicUpdReqVO.setUserName(companyPersonal.getPersonalName());
        devicePicUpdReqVO.setIden(Iden.TEACHER);
        devicePicUpdReqVO.setPicType(PicType.URL);
        devicePicUpdReqVO.setResp(companyPersonal.getIcon());
        deviceService.UpdeviceBaseHand(companyPersonal.getCompanyId(), devicePicUpdReqVO);
        return true;

    }

    @Transactional
    public boolean issueBatchPersonal(List<Long> companyPersonalIds) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.in(companyPersonalIds));
        List<CompanyPersonal> companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetch();
        companyPersonals.stream().forEach(ct -> {
            DevicePicAddVO devicePicAddVO = new DevicePicAddVO();
            devicePicAddVO.setUserId(Iden.STUDENT + "_" + String.valueOf(ct.getId()));
            devicePicAddVO.setUserName(ct.getPersonalName());
            devicePicAddVO.setIden(Iden.STUDENT);
            devicePicAddVO.setPicType(PicType.URL);
            devicePicAddVO.setResp(ct.getIcon());
            deviceService.AdddeviceBaseHand(ct.getCompanyId(), devicePicAddVO);
        });

        return true;

    }

    @Transactional
    public boolean deleteByCompanyPersonalId(long companyPersonalId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(companyPersonalId));
        List<Relationship> relationships = relationshipService.relationshipsList(0, companyPersonalId);
        relationships.stream().forEach(rs -> {
            relationshipService.deleteByRelationshipId(rs.getId());
        });
        CompanyPersonal CompanyPersonal;
        queryFactory.select();
        CompanyPersonal = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue()).fetchOne();
        if (CompanyPersonal == null) return false;
        deleteImgPersonal(CompanyPersonal.getId());
        entityManager.remove(CompanyPersonal);
//            entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
        return true;

    }

    @Transactional
    public boolean deleteBatchPersonal(List<Long> companyPersonalIds) {
        companyPersonalIds.stream().forEach(cp -> {
            if (!deleteByCompanyPersonalId(cp))
                throw new VerificationException(ReplRyCode.BATCH_REMOV_ERROR, ReplRyCode.BATCH_REMOV_ERROR.getMessage());
        });
        return true;

    }


    @Transactional
    public CompanyPersonalDTO updataByCompanyPersonalId(UpdateEntityVO<CompanyPersonalVO> updateCompanyPersonalVO) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        CompanyPersonalVO companyPersonalVO = updateCompanyPersonalVO.getEntityVO();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(updateCompanyPersonalVO.getId()));
        CompanyPersonal companyPersonal;
        try {
            companyPersonal = queryFactory
                    .select(qCompanyPersonal)
                    .from(qCompanyPersonal)
                    .where(booleanBuilder.getValue()).fetchOne();
            if (companyPersonal == null)
                throw new VerificationException(ReplRyCode.COMPANY_PERSONAL_NOT_DATA, ReplRyCode.COMPANY_PERSONAL_NOT_DATA.getMessage());
            if (!StringUtils.isEmpty(companyPersonalVO.getPersonalName()))
                companyPersonal.setPersonalName(companyPersonalVO.getPersonalName());
            if (!StringUtils.isEmpty(companyPersonalVO.getGender()))
                companyPersonal.setGender(GenderType.map.get(companyPersonalVO.getGender()));
            if (!StringUtils.isEmpty(companyPersonalVO.getPersonalType()))
                companyPersonal.setPersonalType(PersonalType.map.get(companyPersonalVO.getPersonalType()));
            if (companyPersonalVO.getCompanyId() != 0)
                companyPersonal.setCompanyId(companyPersonalVO.getCompanyId());
            if (companyPersonalVO.getClsId() != 0)
                companyPersonal.setClsId(companyPersonalVO.getClsId());
            if (!StringUtils.isEmpty(companyPersonalVO.getIcon())) {
                companyPersonal.setIcon(companyPersonalVO.getIcon());
                companyPersonal.setStatus(Status.INITIALIZATION);
                updateImgPersonal(companyPersonal.getId());
            }
            companyPersonal.setUpdateTime(new Date().getTime());
            companyPersonal.setUpdateUser(userId);
            companyPersonal = entityManager.merge(companyPersonal);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
        CompanyPersonalDTO CompanyPersonalDTO = CopyUtil.copyEnty(companyPersonal, CompanyPersonalDTO.class);
        return CompanyPersonalDTO;

    }


    @Transactional
    public void updataAttendanceCompany(long companyId, long attendanceId, List<PersonalType> teacherTypes) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.companyId.eq(companyId));
        booleanBuilder.and(qCompanyPersonal.personalType.in(teacherTypes));
        List<CompanyPersonal> companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetch();
        companyPersonals.stream().forEach(ct -> {
            ct.setUpdateUser(userId);
            ct.setUpdateTime(new Date().getTime());
            ct.setAttendanceId(attendanceId);
            entityManager.merge(ct);
        });
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }

    @Transactional
    public void updataGateCompany(long companyId, long gateId, List<PersonalType> teacherTypes) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.companyId.eq(companyId));
        booleanBuilder.and(qCompanyPersonal.personalType.in(teacherTypes));
        List<CompanyPersonal> companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetch();
        companyPersonals.stream().forEach(ct -> {
            ct.setUpdateUser(userId);
            ct.setUpdateTime(new Date().getTime());
            ct.setGateId(gateId);
            entityManager.merge(ct);
        });
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }


    @Transactional
    public void updataAttendancePersonal(long personal, long attendanceId) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(personal));
        CompanyPersonal companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        companyPersonals.setUpdateUser(userId);
        companyPersonals.setUpdateTime(new Date().getTime());
        companyPersonals.setAttendanceId(attendanceId);
        entityManager.merge(companyPersonals);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }


    @Transactional
    public void updataGatePersonal(long personal, long gateId) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(personal));
        CompanyPersonal companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        companyPersonals.setUpdateUser(userId);
        companyPersonals.setUpdateTime(new Date().getTime());
        companyPersonals.setGateId(gateId);
        entityManager.merge(companyPersonals);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }

    @Transactional
    public void updataAttendanceCls(long cls, long attendanceId, List<PersonalType> teacherTypes) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.clsId.eq(cls));
        booleanBuilder.and(qCompanyPersonal.personalType.in(teacherTypes));
        CompanyPersonal companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        companyPersonals.setUpdateUser(userId);
        companyPersonals.setUpdateTime(new Date().getTime());
        companyPersonals.setAttendanceId(attendanceId);
        entityManager.merge(companyPersonals);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }


    @Transactional
    public void updataGateCls(long cls, long gateId, List<PersonalType> teacherTypes) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.clsId.eq(cls));
        booleanBuilder.and(qCompanyPersonal.personalType.in(teacherTypes));
        CompanyPersonal companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        companyPersonals.setUpdateUser(userId);
        companyPersonals.setUpdateTime(new Date().getTime());
        companyPersonals.setGateId(gateId);
        entityManager.merge(companyPersonals);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }


    @Transactional
    public void updataAttendanceDepartment(long department, long attendanceId, List<PersonalType> teacherTypes) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.departmentId.eq(department));
        booleanBuilder.and(qCompanyPersonal.personalType.in(teacherTypes));
        CompanyPersonal companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        companyPersonals.setUpdateUser(userId);
        companyPersonals.setUpdateTime(new Date().getTime());
        companyPersonals.setAttendanceId(attendanceId);
        entityManager.merge(companyPersonals);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }


    @Transactional
    public void updataGateDepartment(long department, long gateId, List<PersonalType> teacherTypes) throws Exception {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.departmentId.eq(department));
        booleanBuilder.and(qCompanyPersonal.personalType.in(teacherTypes));
        CompanyPersonal companyPersonals =
                queryFactory
                        .select(qCompanyPersonal)
                        .from(qCompanyPersonal)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        companyPersonals.setUpdateUser(userId);
        companyPersonals.setUpdateTime(new Date().getTime());
        companyPersonals.setGateId(gateId);
        entityManager.merge(companyPersonals);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
    }


    @Transactional
    public boolean updataByPlOrRule(long pl, long rule) throws Exception {
        UpdateEntityVO<CompanyPersonalVO> updateEntityVO = new UpdateEntityVO<>();
        updateEntityVO.setId(pl);
        CompanyPersonalVO companyPersonalVO = new CompanyPersonalVO();
        companyPersonalVO.setAttendanceId(rule);
        updateEntityVO.setEntityVO(companyPersonalVO);
        CompanyPersonalDTO companyPersonalDTO = updataByCompanyPersonalId(updateEntityVO);
        if (companyPersonalDTO != null) return true;
        return false;
    }

    public List<CompanyPersonalDTO> findBybaseVo(PageEnty<Long> baseVo) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.createUser.eq(baseVo.getBaseId()));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .fetch();
        List<CompanyPersonalDTO> recycleDTOS = CopyUtil.copyList(companyPersonals, CompanyPersonalDTO.class);
        return recycleDTOS;

    }

    public List<CompanyPersonalDTO> findByCreteUser(long CreteUse) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        long createUser = CopyUtil.copyEnty(CreteUse, Long.class);
        booleanBuilder.and(qCompanyPersonal.createUser.eq(createUser));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .fetch();
        List<CompanyPersonalDTO> recycleDTOS = CopyUtil.copyList(companyPersonals, CompanyPersonalDTO.class);
        return recycleDTOS;

    }

    public CompanyPersonal existPersonal(long clsId, String num) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.clsId.eq(clsId));
        booleanBuilder.and(qCompanyPersonal.num.eq(num));
        CompanyPersonal companyPersonal = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .fetchOne();
        return companyPersonal;

    }

    public CompanyPersonal findByPersona(long personalId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(personalId));
        CompanyPersonal companyPersonal = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .fetchOne();
        return companyPersonal;

    }

    public CompanyPersonalDTO findByCompanyPersonalId(long companyPersonalId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(companyPersonalId));
        CompanyPersonal companyPersonal = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue()).fetchOne();
        if (companyPersonal == null) return null;
        CompanyPersonalDTO CompanyPersonalDTO = CopyUtil.copyEnty(companyPersonal, CompanyPersonalDTO.class);
        return CompanyPersonalDTO;

    }

    public List<CompanyPersonal> findByCompanyClsId(long companyClsId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.clsId.eq(companyClsId));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .fetch();
        return companyPersonals;

    }

    public List<CompanyPersonal> findByCompanyId(long companyId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.companyId.eq(companyId));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .fetch();
        return companyPersonals;

    }

    public CompanyPersonal RelationshipPersonalId(long companyPersonalId) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.id.eq(companyPersonalId));
        CompanyPersonal CompanyPersonal = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue()).fetchOne();
        return CompanyPersonal;

    }

    public CompanyPersonal findByRelationship(long clsId, String personalName, String num) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qCompanyPersonal.clsId.eq(clsId));
        booleanBuilder.and(qCompanyPersonal.num.eq(num));
        booleanBuilder.and(qCompanyPersonal.personalName.eq(personalName));
        CompanyPersonal companyPersonal = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue()).fetchOne();
        return companyPersonal;
    }

    public long countPersonalList(PageEnty<CompanyPersonalListVO> companyPersonalListVO) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        long userId = Long.parseLong(VerificationUtil.getUserId());
        CompanyPersonalListVO companyPersonalVO = companyPersonalListVO.getVo();
        if (companyPersonalVO.getCompanyId() != 0) {
            booleanBuilder.and(qCompanyPersonal.companyId.eq(companyPersonalVO.getCompanyId()));
        } else {
            List<Long> companies = companyService.findByBaseId(userId).stream().map(Company::getId).collect(Collectors.toList());
            booleanBuilder.and(qCompanyPersonal.companyId.in(companies));
        }
        if (companyPersonalVO.getCompanyDepartmentId() != 0)
            booleanBuilder.and(qCompanyPersonal.departmentId.eq(companyPersonalVO.getCompanyDepartmentId()));
        if (companyPersonalVO.getCompanyClsId() != 0)
            booleanBuilder.and(qCompanyPersonal.clsId.eq(companyPersonalVO.getCompanyClsId()));
        if (!StringUtils.isEmpty(companyPersonalVO.getGender()))
            booleanBuilder.and(qCompanyPersonal.gender.eq(GenderType.map.get(companyPersonalVO.getGender())));
        if (!StringUtils.isEmpty(companyPersonalVO.getPersonalType()))
            booleanBuilder.and(qCompanyPersonal.personalType.eq(PersonalType.map.get(companyPersonalVO.getPersonalType())));
        if (!StringUtils.isEmpty(companyPersonalVO.getPersonalName()))
            booleanBuilder.and(qCompanyPersonal.personalName.like("%" + companyPersonalVO.getPersonalName() + "%"));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .offset((companyPersonalListVO.getPage() - 1) * companyPersonalListVO.getNum())
                .limit(companyPersonalListVO.getNum())
                .orderBy(qCompanyPersonal.createTime.desc())
                .fetch();
        if (!StringUtils.isEmpty(companyPersonalVO.getStatus()))
            companyPersonals = companyPersonals.stream().filter(ct -> ct.getStatus().equals(Status.map.get(companyPersonalVO.getStatus()))).collect(Collectors.toList());

        return companyPersonals.size();
    }


    public List<CompanyPersonalListDTO> pagePersonalList(PageEnty<CompanyPersonalListVO> companyPersonalListVO) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        List<CompanyPersonalListDTO> recycleDTOS = Lists.newArrayList();
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        CompanyPersonalListVO companyPersonalVO = companyPersonalListVO.getVo();
        if (companyPersonalVO.getCompanyId() != 0) {
            booleanBuilder.and(qCompanyPersonal.companyId.eq(companyPersonalVO.getCompanyId()));
        } else {
            List<Long> companies = companyService.findByBaseId(userId).stream().map(Company::getId).collect(Collectors.toList());
            booleanBuilder.and(qCompanyPersonal.companyId.in(companies));
        }
        if (companyPersonalVO.getCompanyDepartmentId() != 0)
            booleanBuilder.and(qCompanyPersonal.departmentId.eq(companyPersonalVO.getCompanyDepartmentId()));
        if (companyPersonalVO.getCompanyClsId() != 0)
            booleanBuilder.and(qCompanyPersonal.clsId.eq(companyPersonalVO.getCompanyClsId()));
        if (!StringUtils.isEmpty(companyPersonalVO.getGender()))
            booleanBuilder.and(qCompanyPersonal.gender.eq(GenderType.map.get(companyPersonalVO.getGender())));
        if (!StringUtils.isEmpty(companyPersonalVO.getPersonalType()))
            booleanBuilder.and(qCompanyPersonal.personalType.eq(PersonalType.map.get(companyPersonalVO.getPersonalType())));
        if (!StringUtils.isEmpty(companyPersonalVO.getPersonalName()))
            booleanBuilder.and(qCompanyPersonal.personalName.like("%" + companyPersonalVO.getPersonalName() + "%"));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .offset((companyPersonalListVO.getPage() - 1) * companyPersonalListVO.getNum())
                .limit(companyPersonalListVO.getNum())
                .orderBy(qCompanyPersonal.createTime.desc())
                .fetch();
        if (!StringUtils.isEmpty(companyPersonalVO.getStatus()))
            companyPersonals = companyPersonals.stream().filter(ct -> ct.getStatus().equals(Status.map.get(companyPersonalVO.getStatus()))).collect(Collectors.toList());
        companyPersonals.stream().forEach(cp -> {
            CompanyPersonalListDTO companyPersonalListDTO = CopyUtil.copyEnty(cp, CompanyPersonalListDTO.class);
            CompanyDTO companyDTO = companyService.findByCompanyId(cp.getCompanyId());
            companyPersonalListDTO.setCompanyName(companyDTO.getCompanyName());
            if (cp.getDepartmentId() != 0) {
                CompanyDepartmentDTO companyDepartmentDTO = companyDepartmentService.findByCompanyDepartmentId(cp.getDepartmentId());
                companyPersonalListDTO.setDepartmentName(companyDepartmentDTO.getGradeName());
            }
            if (cp.getClsId() != 0) {
                CompanyClsDTO companyClsDTO = companyClsService.findByCompanyClsId(cp.getClsId());
                companyPersonalListDTO.setClsName(companyClsDTO.getClsName());
            }
            recycleDTOS.add(companyPersonalListDTO);
        });
        return recycleDTOS;

    }


    public long countAttendancePersonalList(PageEnty<AttendancePersonalListVO> companyPersonalListVO) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        long userId = Long.parseLong(VerificationUtil.getUserId());
        AttendancePersonalListVO companyPersonalVO = companyPersonalListVO.getVo();
        if (companyPersonalVO.getCompanyId() != 0) {
            booleanBuilder.and(qCompanyPersonal.companyId.eq(companyPersonalVO.getCompanyId()));
        } else {
            List<Long> companies = companyService.findByBaseId(userId).stream().map(Company::getId).collect(Collectors.toList());
            booleanBuilder.and(qCompanyPersonal.companyId.in(companies));
        }
        if (companyPersonalVO.getCompanyDepartmentId() != 0)
            booleanBuilder.and(qCompanyPersonal.departmentId.eq(companyPersonalVO.getCompanyDepartmentId()));
        if (companyPersonalVO.getCompanyClsId() != 0)
            booleanBuilder.and(qCompanyPersonal.clsId.eq(companyPersonalVO.getCompanyClsId()));
        if (companyPersonalVO.getPersonalType().size() > 0) {
            List<PersonalType> personalTypes = Lists.newArrayList();
            companyPersonalVO.getPersonalType().stream().forEach( cp ->{
                personalTypes.add(PersonalType.map.get(cp));
            });
            booleanBuilder.and(qCompanyPersonal.personalType.in(personalTypes));
        }
        if (!StringUtils.isEmpty(companyPersonalVO.getPersonalName()))
            booleanBuilder.and(qCompanyPersonal.personalName.like("%" + companyPersonalVO.getPersonalName() + "%"));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .offset((companyPersonalListVO.getPage() - 1) * companyPersonalListVO.getNum())
                .limit(companyPersonalListVO.getNum())
                .orderBy(qCompanyPersonal.createTime.desc())
                .fetch();
        return companyPersonals.size();
    }


    public List<CompanyPersonalListDTO> pageAttendancePersonalList(PageEnty<AttendancePersonalListVO> companyPersonalListVO) {
        QCompanyPersonal qCompanyPersonal = QCompanyPersonal.companyPersonal;
        List<CompanyPersonalListDTO> recycleDTOS = Lists.newArrayList();
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        AttendancePersonalListVO companyPersonalVO = companyPersonalListVO.getVo();
        if (companyPersonalVO.getCompanyId() != 0) {
            booleanBuilder.and(qCompanyPersonal.companyId.eq(companyPersonalVO.getCompanyId()));
        } else {
            List<Long> companies = companyService.findByBaseId(userId).stream().map(Company::getId).collect(Collectors.toList());
            booleanBuilder.and(qCompanyPersonal.companyId.in(companies));
        }
        if (companyPersonalVO.getCompanyDepartmentId() != 0)
            booleanBuilder.and(qCompanyPersonal.departmentId.eq(companyPersonalVO.getCompanyDepartmentId()));
        if (companyPersonalVO.getCompanyClsId() != 0)
            booleanBuilder.and(qCompanyPersonal.clsId.eq(companyPersonalVO.getCompanyClsId()));
        if (companyPersonalVO.getPersonalType().size() > 0) {
            List<PersonalType> personalTypes = Lists.newArrayList();
            companyPersonalVO.getPersonalType().stream().forEach( cp ->{
                personalTypes.add(PersonalType.map.get(cp));
            });
            booleanBuilder.and(qCompanyPersonal.personalType.in(personalTypes));
        }
        if (!StringUtils.isEmpty(companyPersonalVO.getPersonalName()))
            booleanBuilder.and(qCompanyPersonal.personalName.like("%" + companyPersonalVO.getPersonalName() + "%"));
        List<CompanyPersonal> companyPersonals = queryFactory
                .select(qCompanyPersonal)
                .from(qCompanyPersonal)
                .where(booleanBuilder.getValue())
                .offset((companyPersonalListVO.getPage() - 1) * companyPersonalListVO.getNum())
                .limit(companyPersonalListVO.getNum())
                .orderBy(qCompanyPersonal.createTime.desc())
                .fetch();
        companyPersonals.stream().forEach(cp -> {
            CompanyPersonalListDTO companyPersonalListDTO = CopyUtil.copyEnty(cp, CompanyPersonalListDTO.class);
            CompanyDTO companyDTO = companyService.findByCompanyId(cp.getCompanyId());
            companyPersonalListDTO.setCompanyName(companyDTO.getCompanyName());
            if (cp.getDepartmentId() != 0) {
                CompanyDepartmentDTO companyDepartmentDTO = companyDepartmentService.findByCompanyDepartmentId(cp.getDepartmentId());
                companyPersonalListDTO.setDepartmentName(companyDepartmentDTO.getGradeName());
            }
            if (cp.getClsId() != 0) {
                CompanyClsDTO companyClsDTO = companyClsService.findByCompanyClsId(cp.getClsId());
                companyPersonalListDTO.setClsName(companyClsDTO.getClsName());
            }
            recycleDTOS.add(companyPersonalListDTO);
        });
        return recycleDTOS;

    }

}
